<?php

namespace app\admin\model;

use app\admin\validate\User as ValidateUser;
use think\Model;

class User extends Model
{
    //获取所有用户
    public function getallusers($data)
    {
        $result = db('user')
            ->where($data["where"])
            ->order($data['sort'], $data['sortOrder'])
            ->limit($data["limit"])->page($data["page"])
            ->select();
            $count = db('user')
            ->where($data["where"])
            ->count();
        return json(["rows" => $result, "total" => $count]);
    }
	
	
	//新增用户
    public function add($data)
    {
        $validate = new ValidateUser();
        if(!$validate->scene('add')->check($data)){
            return $validate->getError();
        }
        $usernamers = $this->where("username",$data["username"])->find();
        if($usernamers){
            return "已存在该用户！！";
        }
        $data["salt"] = getRandChar(6);
        $data["password"] = md5($data["password"]);
        $data["viptime"] = time();
        $data["create_time"] = date("Y-m-d H:s:i",time());
        $result = $this->allowField(true)->save($data);
        if($result > 0){
            return 1;
        }else{
            return "服务器错误";
        }
    }

	//修改用户状态
    public function editstatus($id,$userstate = 0)
    {
        if(!is_array($id)){
            return "服务器错误";
        }
        if($userstate == 0){
            //启用状态
            foreach($id as $key=>$value){
                $this->where("id",$value)->update(["reasons"=>0]);
            }
            return 1;
        }else{
            foreach($id as $key=>$value){
                $this->where("id",$value)->update(["reasons"=>1]);
            }
            return 1;
        }
    }

    public function deleteuser($id)
    {
        if(!is_array($id)){
            return "服务器错误";
        }
        foreach($id as $key=>$value){
            $this->where("id",$value)->delete();
        }
        return 1;
    }

    public function getuserinfo($id)
    {
        $result = $this->where("id",$id)->find();
        return $result;
    }

    public function edit($data)
    {
        $data["viptime"] = strtotime($data["viptime"]);
        $validate = new ValidateUser();
        if(!$validate->scene('edit')->check($data)){
            return $validate->getError();
        }
        $id = $data["id"];
        unset($data["id"]);
        if($data["password"] == ""){
            unset($data["password"]);
        }else{
            $userinfo = $this->get($id);
            $data["password"] = md5($data["password"]);
        }
        $result = $this->allowField(true)->save($data,["id"=>$id]);
        if($result){
            return 1;
        }else{
            return "服务器错误";
        }
    }
}